import React, { useEffect, useState, Suspense } from "react";
import { createBrowserRouter, RouterProvider } from "react-router";
import { getRoutes } from "../utils/routeConfig";
import pageComponents from "../pages";

// 加载状态组件
const LoadingFallback = () => (
  <div style={{ padding: "20px", textAlign: "center" }}>
    <h2>加载中...</h2>
  </div>
);

// 错误边界组件
const ErrorBoundary = ({ error }) => (
  <div style={{ padding: "20px", textAlign: "center", color: "red" }}>
    <h2>加载失败</h2>
    <p>{error?.message || "未知错误"}</p>
  </div>
);

const DynamicRouter = () => {
  const [routes, setRoutes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    loadRoutes();
  }, []);

  const loadRoutes = async () => {
    try {
      setLoading(true);
      const routeConfigs = await getRoutes();

      // 将配置转换为React Router格式
      const dynamicRoutes = routeConfigs.map((route) => ({
        path: route.path,
        element: (
          <Suspense fallback={<LoadingFallback />}>
            {React.createElement(
              pageComponents[route.component] || pageComponents.NotFound
            )}
          </Suspense>
        ),
        errorElement: <ErrorBoundary />,
      }));

      // 添加404路由
      dynamicRoutes.push({
        path: "*",
        element: (
          <Suspense fallback={<LoadingFallback />}>
            {React.createElement(pageComponents.NotFound)}
          </Suspense>
        ),
      });

      setRoutes(dynamicRoutes);
    } catch (err) {
      setError(err);
    } finally {
      setLoading(false);
    }
  };

  // 重新加载路由配置
  const reloadRoutes = () => {
    setRoutes([]);
    setError(null);
    loadRoutes();
  };

  if (loading) {
    return <LoadingFallback />;
  }

  if (error) {
    return (
      <div style={{ padding: "20px", textAlign: "center" }}>
        <ErrorBoundary error={error} />
        <button
          onClick={reloadRoutes}
          style={{ marginTop: "10px", padding: "10px 20px" }}
        >
          重试
        </button>
      </div>
    );
  }

  if (routes.length === 0) {
    return <div>暂无路由配置</div>;
  }

  const router = createBrowserRouter(routes);
  return <RouterProvider router={router} />;
};

export default DynamicRouter;
